import * as https from 'https';
import * as http from 'http';
import * as url from 'url';
import { apiBaseUrl } from '../config';

// API 客户端配置 - 使用配置文件中的地址
const API_BASE_URL = apiBaseUrl;

console.log(`[API Client] Using API server: ${API_BASE_URL}`);

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

export class ApiClient {
  private static instance: ApiClient;
  private token: string | null = null;

  private constructor() {}

  static getInstance(): ApiClient {
    if (!ApiClient.instance) {
      ApiClient.instance = new ApiClient();
    }
    return ApiClient.instance;
  }

  setToken(token: string) {
    this.token = token;
  }

  private async request<T>(endpoint: string, options: {
    method?: string;
    data?: any;
    params?: Record<string, string>;
  } = {}): Promise<ApiResponse<T>> {
    const { method = 'GET', data, params } = options;
    
    // 构建 URL
    let requestUrl = `${API_BASE_URL}/${endpoint}`;
    if (params) {
      const searchParams = new URLSearchParams(params);
      requestUrl += `?${searchParams.toString()}`;
    }

    const parsedUrl = url.parse(requestUrl);
    const isHttps = parsedUrl.protocol === 'https:';
    const client = isHttps ? https : http;

    return new Promise((resolve, reject) => {
      const requestData = data ? JSON.stringify(data) : undefined;
      
      const headers: Record<string, string | number> = {
        'Content-Type': 'application/json',
        'Content-Length': requestData ? Buffer.byteLength(requestData) : 0,
      };

      // 添加认证头
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      const requestOptions = {
        hostname: parsedUrl.hostname,
        port: parsedUrl.port,
        path: parsedUrl.path,
        method,
        headers
      };

      const req = client.request(requestOptions, (res) => {
        let responseData = '';
        
        res.on('data', (chunk) => {
          responseData += chunk;
        });
        
        res.on('end', () => {
          try {
            const response = JSON.parse(responseData);
            resolve(response);
          } catch (error) {
            reject(new Error('Invalid JSON response'));
          }
        });
      });

      req.on('error', (error) => {
        reject(error);
      });

      if (requestData) {
        req.write(requestData);
      }
      
      req.end();
    });
  }

  async getBrowserCookie(instanceId: string): Promise<{ cookie: string | null }> {
    try {
      console.log(`[API Client] Getting browser cookie for instance: ${instanceId}`);
      console.log(`[API Client] Token: ${this.token ? 'Set' : 'Not set'}`);
      
      const response = await this.request<{ cookie: string | null }>('get_browser_cookie', {
        params: { instance_id: instanceId }
      });
      
      console.log(`[API Client] Response:`, response);
      
      if (response.code === 0) {
        return response.data;
      } else {
        throw new Error(response.msg || '获取cookie失败');
      }
    } catch (error) {
      console.error('[API Client] Failed to get browser cookie:', error);
      return { cookie: null };
    }
  }

  async reportCookie(instanceId: string, cookie: string): Promise<boolean> {
    try {
      console.log(`[API Client] Reporting cookie for instance: ${instanceId}`);
      console.log(`[API Client] Token: ${this.token ? 'Set' : 'Not set'}`);
      console.log(`[API Client] Cookie length: ${cookie.length}`);
      
      const response = await this.request('report_cookie', {
        method: 'POST',
        data: {
          instance_id: instanceId,
          cookie
        }
      });
      
      console.log(`[API Client] Report response:`, response);
      
      return response.code === 0;
    } catch (error) {
      console.error('[API Client] Failed to report cookie:', error);
      return false;
    }
  }
}

export const apiClient = ApiClient.getInstance(); 